import 'package:flutter/material.dart';
import '../utils/note_essay_import_export_util.dart';
import '../models/note.dart';
import '../models/essay_material.dart';
import '../services/database_service.dart';
import '../services/web_database_service.dart';
import '../repositories/note_repository.dart';
import '../repositories/essay_material_repository.dart';

class NoteEssayImportExportScreen extends StatefulWidget {
  const NoteEssayImportExportScreen({Key? key}) : super(key: key);

  @override
  _NoteEssayImportExportScreenState createState() => _NoteEssayImportExportScreenState();
}

class _NoteEssayImportExportScreenState extends State<NoteEssayImportExportScreen> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final List<String> _tabs = ['笔记', '作文素材'];
  
  // 数据库服务
  final DatabaseService _databaseService = DatabaseService();
  final WebDatabaseService _webDatabaseService = WebDatabaseService();
  
  // 仓库
  late NoteRepository _noteRepository;
  late EssayMaterialRepository _essayMaterialRepository;
  
  // 状态
  String _statusMessage = '';
  bool _isLoading = false;
  
  // 数据
  List<Note> _notes = [];
  List<EssayMaterial> _essayMaterials = [];
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _tabs.length, vsync: this);
    _noteRepository = _databaseService.noteRepository;
    _essayMaterialRepository = EssayMaterialRepository();
    _loadData();
  }
  
  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
  
  // 加载数据
  Future<void> _loadData() async {
    setState(() {
      _isLoading = true;
      _statusMessage = '正在加载数据...';
    });
    
    try {
      // 初始化数据库
      await _databaseService.init();
      await _webDatabaseService.init();
      
      // 加载笔记数据
      final notes = await _noteRepository.getAllNotes();
      
      // 加载作文素材数据
      final essayMaterials = await _essayMaterialRepository.getAllEssayMaterials();
      
      setState(() {
        _notes = notes;
        _essayMaterials = essayMaterials;
        _isLoading = false;
        _statusMessage = '数据加载完成，笔记: ${notes.length}，作文素材: ${essayMaterials.length}';
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _statusMessage = '加载数据失败: $e';
      });
    }
  }
  
  // 导出笔记
  Future<void> _exportNotes() async {
    if (_notes.isEmpty) {
      setState(() {
        _statusMessage = '没有笔记可导出';
      });
      return;
    }

    // 显示导出格式选择对话框
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择导出格式', style: TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold)),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.table_chart),
              title: const Text('CSV格式', style: TextStyle(fontFamily: 'FangSong')),
              subtitle: const Text('适合Excel打开编辑', style: TextStyle(fontFamily: 'FangSong', fontSize: 12)),
              onTap: () {
                Navigator.pop(context);
                _exportNotesToCSV();
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.description),
              title: const Text('Word格式', style: TextStyle(fontFamily: 'FangSong')),
              subtitle: const Text('适合打印和阅读', style: TextStyle(fontFamily: 'FangSong', fontSize: 12)),
              onTap: () {
                Navigator.pop(context);
                _exportNotesToWord();
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
          ),
        ],
      ),
    );
  }

  // 导出笔记到CSV
  Future<void> _exportNotesToCSV() async {
    setState(() {
      _isLoading = true;
      _statusMessage = '正在导出笔记到CSV...';
    });

    try {
      final filePath = await NoteEssayImportExportUtil.exportNotesToCSV(_notes);
      setState(() {
        _isLoading = false;
        _statusMessage = filePath != null ? '笔记导出成功: $filePath' : '笔记导出失败';
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _statusMessage = '笔记导出失败: $e';
      });
    }
  }

  // 导出笔记到Word
  Future<void> _exportNotesToWord() async {
    setState(() {
      _isLoading = true;
      _statusMessage = '正在导出笔记到Word...';
    });

    try {
      final filePath = await NoteEssayImportExportUtil.exportNotesToWord(_notes);
      setState(() {
        _isLoading = false;
        _statusMessage = filePath != null ? '笔记导出成功: $filePath' : '笔记导出失败';
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _statusMessage = '笔记导出失败: $e';
      });
    }
  }
  
  // 导入笔记
  Future<void> _importNotes() async {
    setState(() {
      _isLoading = true;
      _statusMessage = '正在导入笔记...';
    });

    try {
      final result = await NoteEssayImportExportUtil.importNotesFromCSVOrExcel();
      
      // 保存导入的笔记到数据库
      if (result.notes.isNotEmpty) {
        await _noteRepository.addNotes(result.notes);
        await _loadData(); // 重新加载数据
      }
      
      setState(() {
        _isLoading = false;
        if (result.hasErrors) {
          _statusMessage = '部分笔记导入成功，共导入 ${result.notes.length} 个笔记，但有 ${result.errors.length} 个错误';
        } else {
          _statusMessage = '成功导入 ${result.notes.length} 个笔记';
        }
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _statusMessage = '导入笔记失败: $e';
      });
    }
  }
  
  // 导出作文素材
  Future<void> _exportEssayMaterials() async {
    if (_essayMaterials.isEmpty) {
      setState(() {
        _statusMessage = '没有作文素材可导出';
      });
      return;
    }

    // 显示导出格式选择对话框
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择导出格式', style: TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold)),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.table_chart),
              title: const Text('CSV格式', style: TextStyle(fontFamily: 'FangSong')),
              subtitle: const Text('适合Excel打开编辑', style: TextStyle(fontFamily: 'FangSong', fontSize: 12)),
              onTap: () {
                Navigator.pop(context);
                _exportEssayMaterialsToCSV();
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.description),
              title: const Text('Word格式', style: TextStyle(fontFamily: 'FangSong')),
              subtitle: const Text('适合打印和阅读', style: TextStyle(fontFamily: 'FangSong', fontSize: 12)),
              onTap: () {
                Navigator.pop(context);
                _exportEssayMaterialsToWord();
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
          ),
        ],
      ),
    );
  }

  // 导出作文素材到CSV
  Future<void> _exportEssayMaterialsToCSV() async {
    setState(() {
      _isLoading = true;
      _statusMessage = '正在导出作文素材到CSV...';
    });

    try {
      final filePath = await NoteEssayImportExportUtil.exportEssayMaterialsToCSV(_essayMaterials);
      setState(() {
        _isLoading = false;
        _statusMessage = filePath != null ? '作文素材导出成功: $filePath' : '作文素材导出失败';
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _statusMessage = '作文素材导出失败: $e';
      });
    }
  }

  // 导出作文素材到Word
  Future<void> _exportEssayMaterialsToWord() async {
    setState(() {
      _isLoading = true;
      _statusMessage = '正在导出作文素材到Word...';
    });

    try {
      final filePath = await NoteEssayImportExportUtil.exportEssayMaterialsToWord(_essayMaterials);
      setState(() {
        _isLoading = false;
        _statusMessage = filePath != null ? '作文素材导出成功: $filePath' : '作文素材导出失败';
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _statusMessage = '作文素材导出失败: $e';
      });
    }
  }
  
  // 导入作文素材
  Future<void> _importEssayMaterials() async {
    setState(() {
      _isLoading = true;
      _statusMessage = '正在导入作文素材...';
    });

    try {
      final result = await NoteEssayImportExportUtil.importEssayMaterialsFromCSVOrExcel();
      
      // 保存导入的作文素材到数据库
      if (result.materials.isNotEmpty) {
        await _essayMaterialRepository.addEssayMaterials(result.materials);
        await _loadData(); // 重新加载数据
      }
      
      setState(() {
        _isLoading = false;
        if (result.hasErrors) {
          _statusMessage = '部分作文素材导入成功，共导入 ${result.materials.length} 个作文素材，但有 ${result.errors.length} 个错误';
        } else {
          _statusMessage = '成功导入 ${result.materials.length} 个作文素材';
        }
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _statusMessage = '导入作文素材失败: $e';
      });
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('笔记与作文素材导入导出', style: TextStyle(fontFamily: 'FangSong')),
        bottom: TabBar(
          controller: _tabController,
          tabs: _tabs.map((tab) => Tab(text: tab)).toList(),
          labelStyle: const TextStyle(fontFamily: 'FangSong'),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          // 笔记导入导出
          _buildNoteTab(),
          
          // 作文素材导入导出
          _buildEssayMaterialTab(),
        ],
      ),
    );
  }
  
  // 构建笔记标签页
  Widget _buildNoteTab() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 状态信息
          if (_statusMessage.isNotEmpty)
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(8.0),
              color: Colors.grey[200],
              child: Text(_statusMessage, style: const TextStyle(fontFamily: 'FangSong')),
            ),
          
          const SizedBox(height: 16.0),
          
          // 导入导出按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              ElevatedButton.icon(
                onPressed: _isLoading ? null : _importNotes,
                icon: const Icon(Icons.upload_file),
                label: const Text('导入笔记', style: TextStyle(fontFamily: 'FangSong')),
              ),
              ElevatedButton.icon(
                onPressed: _isLoading || _notes.isEmpty ? null : _exportNotes,
                icon: const Icon(Icons.download),
                label: const Text('导出笔记', style: TextStyle(fontFamily: 'FangSong')),
              ),
            ],
          ),
          
          const SizedBox(height: 16.0),
          
          // 笔记列表
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _notes.isEmpty
                    ? const Center(child: Text('暂无笔记', style: TextStyle(fontFamily: 'FangSong')))
                    : ListView.builder(
                        itemCount: _notes.length,
                        itemBuilder: (context, index) {
                          final note = _notes[index];
                          return Card(
                            margin: const EdgeInsets.only(bottom: 8.0),
                            child: ListTile(
                              title: Text(note.title, style: const TextStyle(fontFamily: 'FangSong')),
                              subtitle: Text(
                                '${note.category} | ${DateTime.fromMillisecondsSinceEpoch(note.created_at).toString().substring(0, 16)}',
                                style: const TextStyle(fontFamily: 'FangSong'),
                              ),
                            ),
                          );
                        },
                      ),
          ),
        ],
      ),
    );
  }
  
  // 构建作文素材标签页
  Widget _buildEssayMaterialTab() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 状态信息
          if (_statusMessage.isNotEmpty)
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(8.0),
              color: Colors.grey[200],
              child: Text(_statusMessage, style: const TextStyle(fontFamily: 'FangSong')),
            ),
          
          const SizedBox(height: 16.0),
          
          // 导入导出按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              ElevatedButton.icon(
                onPressed: _isLoading ? null : _importEssayMaterials,
                icon: const Icon(Icons.upload_file),
                label: const Text('导入作文素材', style: TextStyle(fontFamily: 'FangSong')),
              ),
              ElevatedButton.icon(
                onPressed: _isLoading || _essayMaterials.isEmpty ? null : _exportEssayMaterials,
                icon: const Icon(Icons.download),
                label: const Text('导出作文素材', style: TextStyle(fontFamily: 'FangSong')),
              ),
            ],
          ),
          
          const SizedBox(height: 16.0),
          
          // 作文素材列表
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _essayMaterials.isEmpty
                    ? const Center(child: Text('暂无作文素材', style: TextStyle(fontFamily: 'FangSong')))
                    : ListView.builder(
                        itemCount: _essayMaterials.length,
                        itemBuilder: (context, index) {
                          final material = _essayMaterials[index];
                          return Card(
                            margin: const EdgeInsets.only(bottom: 8.0),
                            child: ListTile(
                              title: Text(material.title, style: const TextStyle(fontFamily: 'FangSong')),
                              subtitle: Text(
                                '${material.category} | ${material.source} | ${DateTime.fromMillisecondsSinceEpoch(material.createdAt).toString().substring(0, 16)}',
                                style: const TextStyle(fontFamily: 'FangSong'),
                              ),
                            ),
                          );
                        },
                      ),
          ),
        ],
      ),
    );
  }
}